package com.meihua.baoleyi.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {
    public static String encode(String password) {
        try {
            //获取数据摘要器
            MessageDigest digest = MessageDigest.getInstance("MD5");
            //2.摘要数据,返回保存有摘要数据的byte数组
            byte[] bytes = digest.digest(password.getBytes());

            StringBuffer sb = new StringBuffer();
            //3.对每个摘要的数据进行加密操作
            for (byte b : bytes) {
                int i = b & 0xff;
                String hexString = Integer.toHexString(i);
                // System.out.println(hexString);
                if (hexString.length() == 1) {
                    hexString = "0" + hexString;
                }
                //将所有的摘要数据的密文整合在一起得到总的密文
                sb.append(hexString);
            }

            String md5 = sb.toString();

            return md5;
        } catch (NoSuchAlgorithmException e) {
            // 没有此算法异常
            e.printStackTrace();
        }

        return null;
    }

    private MD5() {
    }

    public final static String getMessageDigest(byte[] buffer) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(buffer);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }
}
